<template>
  <view class="order-center-container">
    <!-- 顶部蓝色区域 -->
    <view class="order-header">
      <text class="header-title">订单中心</text>
    </view>

    <!-- 订单状态导航和搜索 -->
    <view class="order-tabs-search">
      <view class="order-tabs">
        <text :class="['tab-item', currentTab === 0 ? 'active' : '']" @click="changeTab(0)">未付款</text>
        <text :class="['tab-item', currentTab === 1 ? 'active' : '']" @click="changeTab(1)">已付款</text>
      </view>
      <image class="search-icon" src="/static/search-icon.png" mode="aspectFit"></image>
    </view>

    <!-- 订单列表滚动区域 -->
    <scroll-view class="order-list-scroll" scroll-y="true">
      <view class="order-card" v-for="(order, orderIndex) in filteredOrderList" :key="orderIndex">
        <view class="order-number">订单编号: {{ order.orderNo }}</view>
        <view class="order-goods-list">
          <view class="goods-item" v-for="(goods, goodsIndex) in order.goods" :key="goodsIndex">
            <image class="goods-img" :src="goods.goodPicture" mode="aspectFill"></image>
            <view class="goods-info">
              <text class="goods-name">{{ goods.goodName }}</text>
              <view class="goods-price-quantity">
                <text class="goods-price">¥{{ goods.goodOriginalPrice.toFixed(2) }}</text>
                <text class="goods-quantity">数量: {{ goods.quantity }}</text>
              </view>
            </view>
          </view>
        </view>
        <view class="order-summary">
          <view class="more-options" v-if="order.payStatus === 1">
            <button class="more-text" @click.stop="deleteOrder(orderIndex)">删除订单</button>
          </view>
          <view class="order-right-summary">
            <div class="order-bottom-row">
              <span class="total-count">共计: {{ order.number }}</span>
              <span class="actual-label-inline">实付</span>
              <span class="price-value-inline">¥{{ order.payAmount.toFixed(2) }}</span>
              <button class="pay-now-btn-inline" v-if="order.payStatus === 0" @click="payNow(order)">立即支付</button>
            </div>
          </view>
        </view>
      </view>
    </scroll-view>

    <tabBar></tabBar>
  </view>
</template>

<script>
	import {
		selectOrder,deleteOrder,payOrder
	} from '@/api/order.js'
export default {
  data() {
    return {
      currentTab: 0, // 当前选中的tab: '0' 或 '1'
      orderList: [
      ]
    };
  },
  computed: {
    filteredOrderList() {
      return this.orderList.filter(order => order.payStatus === this.currentTab);
    }
  },
  onReady:function(){
	  this.selectOrders()
	 //  //获取登录用户信息
	 // const id = uni.getStorageSync('userId')
	 // const type = uni.getStorageSync('role')
	 //  //加载订单数据
	 //  const data={
		//   type,
		//   id,
		//   payStatus:'0'
	 //  }
	 //  //调用api
	 //  selectOrder(data).then(res =>{
		//   console.log(res);
		//   this.orderList = res.data.orders
		//   console.log(this.orderList)
	 //  }).catch(err => {
		//   uni.showToast({
		//     title: '查询订单失败！',
		//     icon: 'error'
		//   });
		//  		console.error('获取订单信息失败:', err)
	 //  	})
  },
  methods: {
    changeTab(tab) {
      this.currentTab = tab;
      this.selectOrders();
    },
	//查询订单
	selectOrders(){
		//获取登录用户信息
		const id = uni.getStorageSync('userId')
		const type = uni.getStorageSync('role')
		 //加载订单数据
		 const data={
				  type,
				  id,
		 }
		//调用api
		selectOrder(data).then(res =>{
			console.log(res);
			this.orderList = res.data.orders
			console.log(this.orderList)
		}).catch(err => {
			uni.showToast({
				title: '查询订单失败！',
				icon: 'error'
			});
			console.error('获取订单信息失败:', err)
		})
	},
	//删除订单按钮
    deleteOrder(index) {
		console.log(this.filteredOrderList[index].orderNo);
      // 仅允许已付款订单删除
      if (this.filteredOrderList[index].payStatus !== 1) return;
      // 实际应用中需要根据订单ID删除，这里使用索引模拟
      uni.showModal({
        title: '提示',
        content: '确定要删除此订单吗？',
        success: (res) => {
          if (res.confirm) {
            const orderToDelete = this.filteredOrderList[index];
            const originalIndex = this.orderList.findIndex(order => order.id === orderToDelete.id && order.payStatus === 1);
            // if (originalIndex !== -1) {
            //   this.orderList.splice(originalIndex, 1);
            //   uni.showToast({
            //     title: '订单删除成功',
            //     icon: 'success'
            //   });
            // }
			//调用api删除订单
			const data = {
				orderNo:orderToDelete.orderNo
			}
			deleteOrder(data).then(res => {
				console.log(res)
				
				if (res.message === "删除成功") {
				  this.selectOrders();
				  uni.showToast({
				    title: '订单删除成功',
				    icon: 'success'
				  });
				}else{
					uni.showToast({
					  title: '订单删除失败',
					  icon: 'error'
					});
				}
			}).catch(err=>{
				uni.showToast({
				  title: '删除订单请求访问失败',
				  icon: 'error'
				});
			})
			
          }
        }
      });
    },
    payNow(order) {
      // 实现立即支付的逻辑
      console.log('立即支付', order);
	  uni.showModal({
	    title: '确认支付',
	    content: '是否确认支付？',
	    confirmText: '确认支付',
	    cancelText: '取消',
	    success: (modalRes) => {
	      if (modalRes.confirm) {
	        payOrder(order).then(res => {
				console.log(res)
	        		if(res.message === '修改订单成功！'){
	        			uni.showToast({
	        			  title: '支付成功！',
	        			  icon: 'success'
	        			});
	        			this.selectOrders()
	        		}else{
						uni.showToast({
						  title: '支付失败！',
						  icon: 'success'
						});
					}
	        }).catch(err=> {
	        		  uni.showToast({
	        		    title: '支付订单请求访问失败',
	        		    icon: 'error'
	        		  });
	        		  console.log(err)
	        })
	      } 
	    }
	  })
	 
    }
  }
};
</script>

<style scoped>
.order-center-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: linear-gradient(to bottom, #2C57F6 14%, #ffffff 14%);
}

.order-header {
  height: 7.67vh;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  padding-top: 8px;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1;
}

.header-title {
  color: #ffffff;
  font-size: 28px;
  font-weight: bold;
  font-style: italic;
}

.header-buttons {
  display: flex;
  align-items: center;
}

.dot-icon {
  color: #ffffff;
  font-size: 24px;
  margin-right: 10px;
}

.setting-icon {
  width: 24px;
  height: 24px;
}

.order-tabs-search {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  margin-top: 7.67vh; /* 确保在header下方 */
  background-color: #ffffff;
  border-bottom: 1px solid #eee;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
  position: relative;
  z-index: 2;
}

.order-tabs {
  display: flex;
}

.tab-item {
  padding: 5px 15px;
  font-size: 16px;
  color: #666;
  position: relative;
}

.tab-item.active {
  color: #007AFF;
  font-weight: bold;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  left: 50%;
  bottom: -5px;
  transform: translateX(-50%);
  width: 20px;
  height: 2px;
  background-color: #007AFF;
}

.search-icon {
  width: 24px;
  height: 24px;
}

.order-list-scroll {
  flex: 1;
  padding: 10px;
  background-color: #ffffff;
  padding-top: 10px;
  padding-bottom: 80px;
}

.order-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 15px;
  padding: 15px;
  border: 1px solid #afa8a88f;
  margin-right: 20px;
}

.order-number {
  font-size: 14px;
  color: #999;
  margin-bottom: 10px;
  padding-bottom: 5px;
  border-bottom: 1px solid #eee;
}

.order-goods-list {
  margin-bottom: 10px;
}

.goods-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.goods-img {
  width: 60px;
  height: 60px;
  border-radius: 5px;
  margin-right: 10px;
}

.goods-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.goods-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.goods-price-quantity {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 5px;
}

.goods-price {
  color: #333;
  font-size: 14px;
  font-weight: bold;
}

.goods-quantity {
  font-size: 14px;
  color: #666;
}

.order-summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
}

.more-options {
  position: relative;
}

.more-text {
  font-size: 14px;
  color: #666;
}

.delete-order-btn {
  position: absolute;
  left: 0;
  top: 18px;
  background-color: #f00;
  color: #fff;
  font-size: 12px;
  padding: 5px 10px;
  border-radius: 4px;
  border: none;
  z-index: 10;
  min-width: unset;
  height: unset;
  line-height: unset;
}

.order-right-summary {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.order-bottom-row {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-end;
  width: 100%;
  box-sizing: border-box;
}

.total-count {
  font-size: 14px;
  color: #666;
  margin-left: 0;
  margin-right: 12px;
}

.actual-label-inline {
  font-size: 13px;
  color: #888;
  margin-right: 4px;
}

.price-value-inline {
  color: #f00;
  font-weight: bold;
  font-size: 18px;
  letter-spacing: 1px;
  margin-right: 12px;
}

.pay-now-btn-inline {
  background-color: #007AFF;
  color: #fff;
  padding: 6px 18px;
  border-radius: 6px;
  font-size: 16px;
  font-weight: bold;
  border: none;
  box-shadow: 0 2px 8px #e6eaff;
  height: 38px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  margin-left: auto;
}

.footer-total {
  font-size: 16px;
}

.total-text {
  margin-left: 0px;
  color: #333;
  font-weight: bold;
  font-size: 20px;
}

.footer-settle {
  background-color: #007AFF;
  color: #fff;
  padding: 4px 25px;
  border-radius: 6px;
  font-size: 16px;
  font-weight: bold;
  border: none;
  margin-left: 0px;
}
</style>